package com.dl.dlcommon.interceptor;

import com.dl.dlcommon.exception.BusiException;
import com.dl.dlcommon.exception.LoginException;
import com.dl.dlcommon.interceptor.exception.ExceptionHandlerStrategy;
import com.dl.dlcommon.interceptor.exception.impl.BusiExceptionHandler;
import com.dl.dlcommon.interceptor.exception.impl.GlobalExceptionHandler;
import com.dl.dlcommon.interceptor.exception.impl.LoginExceptionHandler;
import com.dl.dlcommon.utils.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * 全局异常处理
 * @author DL
 * @create 2022-12-26 15:53
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionInterceptor{

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        // 处理aop或者事务对异常进行包装的情况
        if (e instanceof UndeclaredThrowableException) {
            e = (Exception) ((UndeclaredThrowableException) e).getUndeclaredThrowable();
        }

        if ("No static resource favicon.ico.".equals(e.getMessage())){
            return Result.ok();
        }
        ExceptionHandlerStrategy strategy = getExceptionHandlerStrategy(e);
        return strategy.handleException(e);
    }


    /**
     * 获取异常处理策略
     * @param e 异常信息
     * @return {@link ExceptionHandlerStrategy }
     * @author DL
     * @date 2024/04/08
     */
    public static ExceptionHandlerStrategy getExceptionHandlerStrategy(Exception e) {

        if (e instanceof LoginException) {
            return new LoginExceptionHandler();
        }else if (e instanceof BusiException){
            return new BusiExceptionHandler();
        } else {
            return new GlobalExceptionHandler();
        }
    }

}
